import React, { useState, useRef, useEffect, useContext } from 'react';
import styles from './baseInfo.module.less';
import {
    Button,
    Card,
    Col,
    List,
    Row,
    Avatar,
    Tooltip,
    Modal,
    Form,
    Input,
    Select,
    InputNumber,
    Upload,
    message,
    Spin
} from "antd";
import {
    CommentOutlined,
    NotificationOutlined,
    UserOutlined,
    AntDesignOutlined,
    PlusSquareOutlined,
    EditOutlined,
    SettingOutlined,
    EllipsisOutlined,
    PlusOutlined,
} from '@ant-design/icons';
import * as PropTypes from "prop-types";
import { useTranslation } from 'react-i18next';
import PieDonut2 from "../../components/HighCharts/PieDonutCharts2";
import ImgCom from '@src/components/ImgCom';
import dobleModalConfig from '@src/utils/dobleModalConfig';

import {
    getCompanyInfo,
    editCompanyInfo,
    editCompanyBusiness,
    editCompanyInfoApi,
    switchEquipmentSupplierApi
} from '@src/services/company';

import { PublicDataStore } from '@src/store/PublicData/Provider';
import request from "@src/services/request";
import { getMyInvited, getUser, uploadALiFile } from "@src/services/user";
import { getMyBidding } from "@src/services/biddingProject";


function Flex(props) {
    return null;
}

Flex.propTypes = {
    gap: PropTypes.string,
    wrap: PropTypes.bool,
    children: PropTypes.node
};

const BaseInfo = () => {
    const editBaseFormRef = useRef(null);
    const editBusinessFormRef = useRef(null);
    const { dispatch, state } = useContext(PublicDataStore);
    const { t } = useTranslation();

    const [getCompanyLoading, setGetCompanyLoading] = useState(false);
    const [companyInfoData, setCompanyInfoData] = useState({});
    const [editBaseInfoVisible, setEditBaseInfoVisible] = useState(false);
    const [editBaseInfoLoading, setEditBaseInfoLoading] = useState(false);
    const [isCompanyProfileEdit, setIsCompanyProfileEdit] = useState(false);
    const [editBusinessVisible, setEditBusinessVisible] = useState(false);
    const [editBusinessLoading, setEditBusinessLoading] = useState(false);

    const [imageUrl, setImageUrl] = useState('');
    const [imageFile, setImageFile] = useState({});
    const [companyInfo, setCompanyInfo] = useState();
    const [companyInfoLoading, setCompanyInfoLoading] = useState(false);
    const [equipmentSupplierLoading, setEquipmentSupplierLoading] = useState(false);
    const [invitedList, setInvitedList] = useState([]);
    const [utm_invite_code, setInviteCode] = useState([]);
    const [biddingList, setBiddingList] = useState([]);

    useEffect(() => {
        onGetCompanyLoad();
    }, []);

    const onGetCompanyLoad = async () => {
        setGetCompanyLoading(true);
        const res = await getCompanyInfo();

        if (!res) return;

        setGetCompanyLoading(false);
        setCompanyInfoData(res);
        setImageUrl(res.logo_path);
        setCompanyInfo(res?.company_profile || '');
        dispatch({
            type: 'SET_COMPANY_INFO',
            payload: res
        })
        getMyInvited().then(r => setInvitedList(r))
        getUser().then(r => {
            setInviteCode(r.invitation_code)
        })

        const resBidding = await getMyBidding();
        setBiddingList(resBidding);

    }

    const onCancelEditBase = () => {
        setEditBaseInfoVisible(false);
        editBaseFormRef.current.resetFields();
        setImageFile({});
        setImageUrl(companyInfoData.logo_path);
    }


    // 修改公司信息
    const onEditBaseFinish = async (data) => {
        setEditBaseInfoLoading(true);

        const fileUrl = await uploadALiFile(imageFile, 'logo');

        const res = await editCompanyInfo({
            ...data,
            company_logo: fileUrl?.[0] || '',
        });

        setEditBaseInfoLoading(false);
        if (!res) return;

        message.success(res.message);
        onGetCompanyLoad();
        setEditBaseInfoVisible(false);
    }

    // 修改公司业务范围
    const onEditBusinessFinish = async (data) => {
        setEditBusinessLoading(true);

        const res = await editCompanyBusiness(data);

        setEditBusinessLoading(false);

        if (!res) return;
        message.success(res.message);
        onCancelEditBusiness();
        onGetCompanyLoad();
    }

    const onCancelEditBusiness = () => {
        setEditBusinessVisible(false);
        editBusinessFormRef.current.resetFields();

    }

    const getBase64 = (img, callback) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    };

    const beforeUpload = (file) => {
        if (!(file.type.includes('image/png') || file.type.includes('image/jpeg'))) {
            message.error(t("Please upload a file in png or jpg format"));

            return;
        }

        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error(t('Image must be smaller than 2MB!'));

            return;
        }

        getBase64(file, url => {
            setImageUrl(url)
        });
        setImageFile(file);

        return;
    };

    const editCompanyInfoLoad = async (text) => {
        setCompanyInfoLoading(true);

        const res = await editCompanyInfoApi({
            company_profile: text
        });

        message.success(res.message);
        onGetCompanyLoad();
        setCompanyInfoLoading(false);

        return res;
    }

    // 切换公司简介编辑态
    const onCompanyInfoSwitchEdit = async () => {

        let text = companyInfo;
        const newEditType = !isCompanyProfileEdit;

        if (!isCompanyProfileEdit) {
            text = symbolFormat(companyInfo);
        } else {
            text = htmlForamt(companyInfo);
        }

        // 未修改
        if (text === companyInfoData.company_profile) {
            setCompanyInfo(text);
            setIsCompanyProfileEdit(newEditType);
            return;
        }

        if (!newEditType) {
            const res = await editCompanyInfoLoad(text);
            if (res?.code !== 0) return;
        }

        setCompanyInfo(text);
        setIsCompanyProfileEdit(newEditType);
    }

    // 公司简介
    const onEditCompanyInfo = (e) => {
        setCompanyInfo(e.target.value);
    };

    const htmlForamt = (value) => {
        return value.replace(/ /g, '&nbsp;').replace(/\n/g, '<br />');
    }

    const symbolFormat = (value) => {
        return value.replace(/&nbsp;/g, ' ').replace(/<br \/>/g, '\n');
    }

    // 开关 设备供应方
    const onSwitchEquipmentSupplier = async () => {
        const configFlag = await dobleModalConfig(!companyInfoData?.supplier ? t('Are you sure you want to activate the device supplier identity?') : t('Are you sure you want to close the device provider identity?'));
        if (!configFlag) return;

        setEquipmentSupplierLoading(true);

        const res = await switchEquipmentSupplierApi({
            status: !companyInfoData?.supplier
        });

        setEquipmentSupplierLoading(false);
        if (res?.code === 0) {
            message.success(res.message);
            onGetCompanyLoad();
        }
    }

    const UploadButton = (
        <div>
            <PlusOutlined />
            <div
                style={{
                    marginTop: 8,
                }}
            >
                {t('Upload')}
            </div>
        </div>
    );

    const copyToClipboard = () => {
        const protocol = window.location.protocol;
        const domain = window.location.hostname;
        const port = window.location.port;
        let hostAddress = protocol + "//" + domain;
        if (port) {
            hostAddress += ":" + port;
        }
        const textToCopy = `给你推荐一个宝藏产品，点击 ${hostAddress}/invite?utm_invite_code=${utm_invite_code} 登录IT解决方案平台网页端，发送一轮对话，咱俩都能免费领会员(建议PC端领取，体验更加丝滑哦~)。`;
        navigator.clipboard.writeText(textToCopy)
            .then(() => {
                message.success(t('Invitation text copied to clipboard'));
            })
            .catch(err => {
                message.error(`${t('Copy Failure')}：`, err);
            });
    };

    return (
        <Spin spinning={getCompanyLoading}>
            <div className={styles.baseinfo_box}>
                <Row style={{ flexWrap: 'nowrap', height: '100%' }}>
                    <Col span={7} className={styles.leftSpan}>
                        <div className={styles.leftSpanBG}>
                            <div>
                                <p>
                                    <b>Hi Admin</b>
                                </p>
                                <p>
                                    {t('Good morning')}!
                                </p>
                            </div>
                            <div className={styles.noticeSpan}>
                                <CommentOutlined style={{ fontSize: '30px', color: '#08c' }} />
                                <NotificationOutlined style={{ fontSize: '30px', color: '#08c', margin: '0 10px' }} />
                            </div>

                            <div className={styles.logo}>
                                <ImgCom src={companyInfoData.logo_path} alt='logo' />
                            </div>

                            <div className={styles.name}>
                                {companyInfoData.company_name}
                            </div>
                            <div className={styles.info}>
                                {companyInfoData.description}
                            </div>
                            <Row className={styles.dataInfo}>
                                <Col span={8}>
                                    <p className={styles.dataNum}>18</p>
                                    <p>{t('Data Center')}</p>
                                </Col>
                                <Col span={8}>
                                    <p className={styles.dataNum}>5</p>
                                    <p>{t('Invited to quote')}</p>
                                </Col>
                                <Col span={8}>
                                    <p className={styles.dataNum}>30</p>
                                    <p>{t('Follow me')}</p>
                                </Col>
                            </Row>

                            <Row className={styles.dataInfo} justify="space-between">
                                <Col span={12} className={styles.card}>
                                    <div style={{ backgroundColor: '#bdb3b3', borderRadius: 10 }} className={styles.box}>
                                        <p className={styles.cardName}>{t('Equipment Supplier')}</p>
                                        <p className={styles.cardInfo}>{t('Own data center, dedicated line and other resources')}</p>
                                        <p><Button type="primary" loading={equipmentSupplierLoading}
                                            onClick={onSwitchEquipmentSupplier}>{companyInfoData?.supplier ? '已开通' : '未开通'}</Button>
                                        </p>
                                    </div>
                                </Col>
                                <Col span={12} className={styles.card}>
                                    <div style={{ backgroundColor: '#79b17e', borderRadius: 10 }} className={styles.box}>
                                        <p className={styles.cardName}>{t('Procurement Demand')}</p>
                                        <p className={styles.cardInfo}>{t('Need to purchase network resources and seek solutions')}</p>
                                        <p><Button type="primary">{t('Opened')}</Button></p>
                                    </div>
                                </Col>
                            </Row>
                            <Row>
                                <Button onClick={copyToClipboard} type="primary" block className={styles.mgt20}>
                                    {t('Click to copy your share link')}
                                </Button>
                            </Row>
                            <Row className={styles.mgt20}>
                                <Col>{t('You have invited users to log in. You will get the following benefits:', { count: '50' })}
                                    <p>*1.{t('Get 100 exposures of corporate information.')}</p>
                                    <p>*2.{t('Get the latest clues email 10 times.')}</p>
                                    <p>*3.{t('The demand will be pinned for 3 days.')}</p>
                                </Col>
                            </Row>
                        </div>
                    </Col>
                    <Col span={10} className={styles.centerSpan}>
                        <div className={`${styles.centerSpanBG} ${styles.compInfoBase}`}>
                            <div className={styles.title_box}>
                                <h1 className={styles.compTitle}>{t('Basic information of the company')}</h1>
                                <EditOutlined className={styles.icon} onClick={() => setEditBaseInfoVisible(true)} />
                            </div>
                            <Row gutter={16}>
                                <Col span={12}>
                                    <p className={styles.compTip}>{t('Address')}</p>
                                    <p className={styles.compAns}>{companyInfoData.company_address || '-'}</p>
                                </Col>
                                <Col span={12}>
                                    <p className={styles.compTip}>{t('Scale')}</p>
                                    <p className={styles.compAns}>{companyInfoData.scale ? `${companyInfoData.scale}人` : '-'}</p>
                                </Col>
                                <Col span={12}>
                                    <p className={styles.compTip}>{t('Registered capital')}</p>
                                    <p className={styles.compAns}>{companyInfoData.registered_capital || '-'}</p>
                                </Col>
                                <Col span={12}>
                                    <p className={styles.compTip}>{t('Contact Details')}</p>
                                    <p className={styles.compAns}>{companyInfoData.contact_details || '-'}</p>
                                </Col>
                            </Row>

                        </div>
                        <div className={`${styles.centerSpanBG} ${styles.business_scope}`}>
                            <h1 className={styles.compTitle}>{t('Business scope')}</h1>

                            <Row className={`${styles.dataInfo} ${styles.mgt20}`} gutter={16}>
                                <Col align="flex-start" className={styles.tal}>
                                    {
                                        companyInfoData?.company_business?.map(item => (
                                            <Button type="primary" className={styles.mg10}
                                                key={item.business_id}>{item.business_name}</Button>
                                        ))
                                    }
                                    <PlusSquareOutlined
                                        onClick={() => setEditBusinessVisible(true)}
                                        style={{
                                            fontSize: '30px',
                                            float: "right",
                                            margin: "10px 30px 0 0",
                                            cursor: 'pointer'
                                        }} />
                                </Col>

                            </Row>


                        </div>
                        <div className={`${styles.centerSpanBG} ${styles.company_profile}`}>
                            <Spin spinning={companyInfoLoading}>
                                <Card
                                    actions={[
                                        <EditOutlined key="edit" onClick={onCompanyInfoSwitchEdit} />,
                                        // <SettingOutlined key="setting" />,
                                        // <EllipsisOutlined key="ellipsis" />,
                                    ]}
                                    style={{ minWidth: 300 }}>
                                    <Card.Meta
                                        // avatar={<Avatar src="/img/logo.svg" />}
                                        title={t('Company Profile')}
                                        description={
                                            <>
                                                {
                                                    isCompanyProfileEdit ?
                                                        <Input.TextArea
                                                            value={companyInfo}
                                                            onChange={onEditCompanyInfo}
                                                            style={{ minHeight: 300 }}
                                                            maxLength={500}
                                                            showCount
                                                        />
                                                        : (
                                                            <div style={{ minHeight: '100%' }}
                                                                dangerouslySetInnerHTML={{ __html: companyInfo }}>
                                                            </div>
                                                        )
                                                }
                                            </>
                                        }
                                    />
                                </Card>
                            </Spin>
                        </div>
                    </Col>
                    <Col xl={7} className={styles.rightSpan}>
                        <div className={`${styles.rightSpanBG} ${styles.quotation_invitation}`}>
                            <h1 className={styles.compTitle}>{t('Receive quotation invitation')}</h1>
                            {Array.isArray(biddingList) ? (
                                <List
                                    itemLayout="horizontal"
                                    dataSource={biddingList.slice(0, 5)}
                                    renderItem={(item, index) => (
                                        <List.Item>
                                            <List.Item.Meta
                                                // avatar={<Avatar src={`https://api.dicebear.com/7.x/miniavs/svg?seed=${index}`} />}
                                                title={<a href="https://ant.design">{item.title}</a>}
                                                description={t('There is an urgent project and I need your quotation')}
                                            />
                                        </List.Item>
                                    )}
                                />
                            ) : (
                                <div></div>
                            )}
                        </div>


                        <div className={`${styles.rightSpanBG} ${styles.mgt20}`}>
                            <Avatar.Group size="large" maxCount={5}
                                max={{ count: 2, style: { color: '#f56a00', backgroundColor: '#fde3cf' } }}>
                                {invitedList?.map && invitedList?.map((inviter, index) => (
                                    <React.Fragment key={index}>
                                        <Avatar style={{ backgroundColor: '#f56a00' }}>{index + 1}</Avatar>
                                    </React.Fragment>
                                ))}
                                <Tooltip title="Invite User" placement="top">
                                    <Avatar style={{ backgroundColor: '#87d068' }} icon={<UserOutlined />} />
                                </Tooltip>
                            </Avatar.Group>
                            <span className={styles.followSpan}>
                                {t('Users I invited')}
                            </span>

                            <div className={styles.mgt20}>
                                <div className={styles.chart_container}>
                                    {invitedList.length === 0 ? t('You have not invited any other users yet') :
                                        <PieDonut2 />}
                                </div>
                            </div>
                        </div>
                    </Col>
                    <Modal
                        open={editBaseInfoVisible}
                        onCancel={onCancelEditBase}
                        footer={null}
                        title={t('Modify basic information')}
                        style={{ width: '540px !important' }} // 设置宽度为540px
                    >
                        <div className={styles.edit_base_info_modal}>
                            <Form layout='vertical' onFinish={onEditBaseFinish} ref={editBaseFormRef}
                                initialValues={companyInfoData}>
                                <Upload
                                    // name="avatar"
                                    listType="picture-card"
                                    className="avatar-uploader"
                                    accept="image/png, image/jpeg"
                                    showUploadList={false}
                                    beforeUpload={beforeUpload}
                                >
                                    {imageUrl ? (
                                        <img
                                            src={imageUrl}
                                            alt="avatar"
                                            style={{
                                                width: '96%',
                                            }}
                                        />
                                    ) : (
                                        UploadButton
                                    )}
                                </Upload>
                                <Form.Item
                                    label={t('Company Name')}
                                    name="company_name"
                                    rules={[
                                        {
                                            required: true,
                                            message: t('Please enter your company name')
                                        },
                                    ]}
                                >
                                    <Input name="company_name" />
                                </Form.Item>
                                <Form.Item
                                    label={t('Company Description')}
                                    name="description"
                                    rules={[
                                        {
                                            required: true,
                                            message: t('Please enter a company description')
                                        },
                                    ]}
                                >
                                    <Input.TextArea
                                        name="description"
                                        maxLength={300}
                                        showCount
                                    />
                                </Form.Item>
                                <Form.Item
                                    label={t('Address')}
                                    name="company_address"
                                    rules={[
                                        {
                                            required: true,
                                            message: t('Please enter your address')
                                        },
                                    ]}
                                >
                                    <Input name="company_address" />
                                </Form.Item>
                                <Row justify="space-between">
                                    <Col span={5}>
                                        <Form.Item
                                            label={t('Company Type')}
                                            name="company_type"
                                            rules={[
                                                {
                                                    required: true,
                                                    message: t('Please enter your company type')
                                                },
                                            ]}
                                        >
                                            <Input name="company_type" />
                                        </Form.Item>
                                    </Col>
                                    <Col span={5}>
                                        <Form.Item
                                            label={t('Scale')}
                                            name="scale"
                                            rules={[
                                                {
                                                    required: true,
                                                    message: t('Please enter the Scale')
                                                },
                                            ]}
                                        >
                                            <Input name="scale" />
                                        </Form.Item>
                                    </Col>
                                    <Col span={5}>
                                        <Form.Item
                                            label={t('Registered capital')}
                                            name="registered_capital"
                                            rules={[
                                                {
                                                    required: true,
                                                    message: t('Please enter the registered capital')
                                                },
                                            ]}
                                        >
                                            <InputNumber name="registered_capital" style={{ width: '100%' }} />
                                        </Form.Item>
                                    </Col>
                                    <Col span={5}>
                                        <Form.Item
                                            label={t('Establishment')}
                                            name="founding_year"
                                            rules={[
                                                {
                                                    required: true,
                                                    message: t('Please enter the company establishment date')
                                                },
                                            ]}
                                        >
                                            <Input name="founding_year" />
                                        </Form.Item>
                                    </Col>
                                </Row>
                                <Form.Item
                                    label={t('Contact Details')}
                                    name="contact_details"
                                    rules={[
                                        {
                                            required: true,
                                            message: t('Please enter contact information')
                                        },
                                    ]}
                                >
                                    <Input name="contact_details" />
                                </Form.Item>
                                <div className={styles.footer_box}>
                                    <Button type='ghost' onClick={onCancelEditBase}>{t('Cancel')}</Button>
                                    <Button type='primary' htmlType='submit'
                                        loading={editBaseInfoLoading}>{t('Sure')}</Button>
                                </div>
                            </Form>
                        </div>
                    </Modal>

                    <Modal
                        open={editBusinessVisible}
                        onCancel={onCancelEditBusiness}
                        footer={null}
                        title={t("Modify the company's business scope")}
                    >
                        <div className={styles.edit_business_modal}>
                            <Form
                                layout='vertical'
                                onFinish={onEditBusinessFinish}
                                ref={editBusinessFormRef}
                            >
                                <Form.Item
                                    label={t('Business scope')}
                                    name="business_id"
                                    rules={[
                                        {
                                            required: true,
                                            message: t("Please select your company's business scope")
                                        },
                                    ]}
                                    initialValue={companyInfoData?.company_business?.map(item => item.business_id) || []}
                                >
                                    <Select
                                        name="business_id"
                                        mode="multiple"
                                        allowClear
                                    >
                                        {
                                            state?.allBusiness?.map(item => (
                                                <Select.Option value={item.business_id}
                                                    key={item.business_id}>{item.business_name}</Select.Option>
                                            ))
                                        }
                                    </Select>
                                </Form.Item>
                                <div className={styles.footer_box}>
                                    <Button type='ghost' onClick={onCancelEditBusiness}>{t('Cancel')}</Button>
                                    <Button type='primary' htmlType='submit'
                                        loading={editBusinessLoading}>{t('Sure')}</Button>
                                </div>
                            </Form>
                        </div>
                    </Modal>
                </Row>
            </div>
        </Spin>
    );
};

export default BaseInfo;
